<template>
  <div>
    <!-- 面包屑导航开始想要修改组件原有样式时尽量把后来修改的样式写在全局样式里面 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 绑定的数据 边框线 隔行变色-->
      <el-table :data="rolesData" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <!-- 使用作用域插槽获取角色下面的权限 -->
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <!-- v-for循环 -->
            <el-row
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
              :class="['tbdbottum',i1==0?'':'tbdtop','center']"
            >
              <!-- 循环渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRolseById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 循环渲染二三级权限 -->
              <el-col :span="19">
                <!-- 渲染二级权限 -->
                <el-row
                  v-for="(item2 , i2) in item1.children"
                  :key="item2.id"
                  :class="[i2==0?'':'tbdtop','center']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRolseById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3,i3) in item2.children"
                      closable
                      @close="removeRolseById(scope.row,item3.id)"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 显示序列号  -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <!-- 操作列引入作用域插槽 -->
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <!-- 分配按钮 -->
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRights(scope.row)" >分配</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog title="权限分配" :visible.sync="IssetRights" width="50%" @close="closeKeysArray">
      <!-- 树形结构 -->
       <el-tree :data="allRightsData" :props="allRightsDataProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="keysArray" ref="treeRef"></el-tree>
        <span slot="footer" class="dialog-footer">
        <el-button @click="IssetRights = false">取 消</el-button>
        <el-button type="primary" @click="commitRights">确 定</el-button>
      </span>
    </el-dialog>    
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesData: [],
      //分配权限的显示与隐藏
      IssetRights:false,
      //所有权限数据
      allRightsData:[],
      allRightsDataProps:{
       children: 'children',
       label: 'authName'
      },
      //默认展开列的id以数组的形式展开 
      keysArray:[],
      rolesId:''
    }
  },
  created() {
    this.getrolesData()
  },
  methods: {
    async getrolesData() {
      const { data: res } = await this.$http.get('roles')
      this.rolesData = res.data
    },
    async removeRolseById(roles, rightsId) {
      //利用messageBox组件弹出确认取消框
      const confirmRes = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(confirmRes)点击确定返回的结果是confirm,点击取消 返回的结果是concel
      if (confirmRes !== 'confirm') {
        return this.$message.info('该操作已经取消')
      }
      //点击删除发送请求
      const { data: res } = await this.$http.delete(
        `roles/${roles.id}/rights/${rightsId}`
      )
      if (res.meta.status !== 200) return this.$message.error('权限删除失败')
      //根据接口文档提示的：返回的data, 是当前角色下最新的权限数据，得出不需要重新再去发请求渲染页面
      //直接将返回的data数据赋值给roles角色的children属性
      roles.children = res.data
      //提示删除成功
      this.$message.success('权限删除成功')
    },
    async showSetRights(roles){
        this.rolesId=roles.id
         //在对话框显示出来之前要先发送请求将数据渲染到对话框中
       const {data : res} = await this.$http.get('rights/tree')
          if(res.meta.status!==200)  return this.$message.error(res.meta.msg)
            this.allRightsData =res.data 
         //显示三级权限的id
        this.getKeys(roles,this.keysArray)

        //点击分配按钮让对话框显示出来
       this.IssetRights=true
    },
    //通过递归获取角色下面所有三级权限的id并且存放到keysArray数组中 ,该方法在分配框显示之前调用
    getKeys(node,arr){
      //角色下不包含children属性就是三级节点
        if(!node.children) {
          //将三级权限下的id放入到keysArray数组
          return arr.push(node.id)
        }
        //循环节点开始递归
      node.children.forEach(item=>this.getKeys(item,arr))
    },
    //监听分配权限框关闭事件,防止keysArray数组中的id越来越多
    closeKeysArray(){
      this.keysArray=[]
    },
    //点击为角色分配权限getCheckedKeys该方法返回的是个数组利用扩展运算符转为数组
   async commitRights(){
   
       const keyArray=[
         ...this.$refs.treeRef.getCheckedKeys(),
         ...this.$refs.treeRef.getHalfCheckedKeys()

       ]
       //转换为字符串（请求参数要求）
       const idStr=keyArray.join(',')
    
       const {data : res}=await this.$http.post(`roles/${this.rolesId}/rights`,{rids:idStr})
        console.log(res)
         if(res.meta.status!==200) return this.$message.error('分配权限失败')
          this.getrolesData()
          this.$message.success('分配权限成功')
          this.IssetRights=false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.tbdtop {
  border-top: 1px solid #eee;
}
.tbdbottum {
  border-top: 1px solid #eee;
}
.center {
  display: flex;
  align-items: center;
}
</style>
